<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-row :gutter="15">
          <el-col :span="6">
            <el-input
              placeholder="请输入内容"
              v-model="paramsInfo.query"
              clearable
              @clear="getUserList"
            ></el-input>
          </el-col>
          <el-col :span="2">
            <el-button
              icon="el-icon-search"
              circle
              @click="getUserList"
            ></el-button
          ></el-col>
          <el-col :span="2"
            ><el-button type="primary" @click="dialogVisible = true"
              >添加</el-button
            ></el-col
          >
        </el-row>

        <el-table :data="userList" style="width: 100%" stripe>
          <el-table-column type="index"></el-table-column>
          <el-table-column prop="username" label="姓名"> </el-table-column>
          <el-table-column prop="email" label="邮箱"> </el-table-column>
          <el-table-column prop="mobile" label="电话"> </el-table-column>
          <el-table-column prop="role_name" label="角色"> </el-table-column>
          <el-table-column prop="mg_state" label="状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                active-color="#13ce66"
                @change="changeMgstate(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="editUser(scope.row.id)"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-share"
                size="mini"
              ></el-button>
              <el-tooltip
                class="item"
                effect="dark"
                content="修改角色"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="warning"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteUserById(scope.row.id)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="paramsInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="paramsInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="50%"
      @close="addCloseDialog"
    >
      <el-form
        :model="userRuleForm"
        :rules="userRules"
        ref="ruleFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userRuleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userRuleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userRuleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="userRuleForm.phone"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog 
    title="提示" :visible.sync="editUserVisible" width="50%"
    @close='resetEditUser'
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        label-width="80px"
        :rules="editFormRules"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop='email'>
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop='mobile'>
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserVisible = false" >取 消</el-button>
        <el-button type="primary" @click="editUserInfo"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getUserList()
  },
  data() {
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/g
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的邮箱'))
    }
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^1[3456789]\d{9}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的手机号'))
    }
    return {
      paramsInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2,
      },
      userList: [],
      total: 0,
      dialogVisible: false,
      userRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15个字符', trigger: 'blur' },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      userRuleForm: {
        username: '',
        password: '',
        email: '',
        phone: '',
      },

      editUserVisible: false,
      editForm: {
        id:'',
        username: '',
        email: '',
        mobile: '',
      },
    }
  },
  methods: {
    getUserList() {
      this.$http.get('users', { params: this.paramsInfo }).then((response) => {
        const { data: res } = response
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.warn('获取用户列表信息失败')
        }
        this.userList = res.data.users
        this.total = res.data.total
      })
    },
    handleSizeChange(size) {
      this.paramsInfo.pagesize = size
      this.getUserList()
    },
    handleCurrentChange(num) {
      this.paramsInfo.pagenum = num
      this.getUserList()
    },
    changeMgstate(obj) {
      this.$http.put(`users/${obj.id}/state/${obj.mg_state}`).then(
        (response) => {
          this.$message.success('更新状态成功')
        },
        (err) => {
          // console.log(err)
          obj.mg_state = !obj.mg_state
          this.$message.error('更新状态失败')
        }
      )
    },
    addCloseDialog() {
      this.$refs.ruleFormRef.resetFields()
    },
    addUser() {
      this.$refs.ruleFormRef.validate((valid) => {
        if (!valid) return
        this.$http.post('users', this.userRuleForm).then((response) => {
          const { data: res } = response
          console.log(res)
          this.$message.success('添加用户成功')
          this.dialogVisible = false
          this.getUserList()
        })
      })
    },
    async editUser(id) {
      this.editUserVisible = true
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return
      this.editForm = res.data
    },
    resetEditUser(){
      this.$refs.editFormRef.resetFields();
    },
    editUserInfo(){
      this.$refs.editFormRef.validate(async (valid) => {
        // console.log(valid)
        if(!valid) return
        //表单数据预校验通过则发送请求
        const {data:res } = await this.$http.put('users/' + this.editForm.id,{
          email:this.editForm.email,
          mobile:this.editForm.mobile
        })
        if(res.meta.status !== 200) return
        this.editUserVisible = false
        this.getUserList()
        this.$message.success('更新用户信息成功')
      })
    },
    async deleteUserById(id){
       const res = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if(res !== 'confirm') {
          return this.$message.info('已取消删除操作')
        }
        const {data:result} =await this.$http.delete('users/'+id)
        console.log(result)
        if(result.meta.status !== 200) {
          return this.$message.error('删除用户失败')
        }
        this.$message.success('删除用户成功')
        this.getUserList();
    }
  },
}
</script>

<style>
</style>